import { reactive } from 'vue'
import * as localforage from 'localforage'
import http from '@/utils/axios'
import { message, Upload } from 'ant-design-vue'

/**
 * 获取OSS签名
 */
const generateSignature = (type) => {
  return http({
    url: `/management-portal/storage/getPostSignature`,
    method: 'GET',
    params: { fileType: type },
  })
}
/**
 * 拼接完整文件名
 */
const generateFileFullName = (prefix, file) => {
  let _prefix = ''
  if (prefix && prefix.length > 0 && typeof prefix === 'string') {
    _prefix = prefix
  } else {
    _prefix = 'untitled'
  }
  return `${_prefix}-${new Date().getTime()}-${file.name}`
}

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

/**
 * 导出Hook
 * @returns { Object }
 */
export default function useUpload(fileNamePrefix) {
  const uploadState = reactive({
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [] as any,
    key: '',
    fullName: '',
    fileProcess: '',
  })

  const handleReset = () => {
    uploadState.previewVisible = false
    uploadState.previewImage = ''
    uploadState.previewTitle = ''
    uploadState.key = ''
    uploadState.fullName = ''
    uploadState.fileList = []
    uploadState.fileProcess = ''
  }

  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }
    uploadState.previewImage = file.url || file.preview
    uploadState.previewVisible = true
    uploadState.previewTitle = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
  }

  const handleCancel = () => {
    uploadState.previewVisible = false
    uploadState.previewTitle = ''
    uploadState.key = ''
    uploadState.fullName = ''
  }

  const handleBeforeUpload = (file) => {
    uploadState.fullName = generateFileFullName(fileNamePrefix, file)
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传JPG或PNG格式图片!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('请上传2MB以下图片!')
    }
    return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE
  }

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      // console.log(generateFileFullName(fileNamePrefix, info.file), " uploading")
      console.log(uploadState.fullName, ' uploading')
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      // console.log(generateFileFullName(fileNamePrefix, info.file), " uploading")
      console.log(uploadState.fullName, ' done')
    }
    if (info.file.status === 'error') {
      // console.log(generateFileFullName(fileNamePrefix, info.file), " upload error!")
      console.log(uploadState.fullName, ' upload error!')
      message.error('upload error')
    }
  }
  const handleRemove = async (file) => {
    uploadState.key = ''
    uploadState.fullName = ''
    uploadState.fileProcess = ''
    // await localforage.removeItem(generateFileFullName(fileNamePrefix, file))
  }

  const handleCustomRequest = async ({ file, onSuccess, onProgress, onError }) => {
    const signature = await generateSignature(file.type.split('/')[0])
    // const key = `${signature.dir}${generateFileFullName(fileNamePrefix, file)}`
    const key = `${signature.dir}${uploadState.fullName}`
    uploadState.key = key
    const formData = new FormData()
    formData.append('name', 'application-icon-' + file.name)
    formData.append('key', key)
    formData.append('policy', signature.policy)
    formData.append('OSSAccessKeyId', signature.accessId)
    formData.append('success_action_status', '200')
    formData.append('signature', signature.signature)
    // formData.append("callback", signature.callback)
    formData.append('file', file)
    const res = await http({
      url: signature.host,
      method: 'post',
      data: formData,
    })
    onSuccess(res)
    console.log('资源上传OSS成功', uploadState.fileList)
  }

  return {
    uploadState,
    handlePreview,
    handleCancel,
    handleBeforeUpload,
    handleChange,
    handleRemove,
    handleCustomRequest,
    handleReset,
  }
}
